package com.formiaomiao.demain.service.impl;

import com.corundumstudio.socketio.SocketIOClient;
import com.formiaomiao.demain.dao.ComplaintDao;
import com.formiaomiao.demain.dao.ComplaintImgDao;
import com.formiaomiao.demain.model.ComplaintBean;
import com.formiaomiao.demain.model.Result;
import com.formiaomiao.demain.service.ComplaintService;
import com.formiaomiao.demain.socket.MessageEventHandler;
import com.formiaomiao.demain.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service(value = "complaintService")
public class ComplaintServiceImpl implements ComplaintService {

    @Autowired
    ComplaintDao complaintDao;
    @Autowired
    ComplaintImgDao complaintImgDao;
    @Autowired
    private JavaMailSender mailSender;

    @Transactional(value = "demain")
    @Override
    public Result<String> InsertComplaint(ComplaintBean bean) {
        StringBuffer sb = new StringBuffer();
        if (complaintDao.InsertComplaint(bean) == 0) {
            return ResultUtil.error(400, "投诉失败");
        } else {
            if (bean.getComplaintImgBean() != null) {
                for (int i = 0; i < bean.getComplaintImgBean().size(); i++) {
                    sb.append(bean.getComplaintImgBean().get(i).getImgurl()+"\n");
                    if (complaintImgDao.InsertImg(bean.getComplaintImgBean().get(i)) == 0) {
                        return ResultUtil.error(400, "投诉失败");
                    }
                }
            }
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                SimpleMailMessage message = new SimpleMailMessage();
                message.setFrom("1013455890@qq.com");
                message.setTo("1013455890@qq.com");
                message.setSubject("用户投诉");
                message.setText(bean.getToid()+bean.getComplaint()+"\n"+sb.toString());
                mailSender.send(message);
                SocketIOClient client = MessageEventHandler.webSocketMap.get(bean.getMac());
                client.sendEvent("messageevent","{\"data\":\"已经收到您的投诉\"}");
            }
        }).start();
        return ResultUtil.success("投诉成功");
    }
}
